package com.ssyc.student.activity;

import android.animation.ObjectAnimator;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.ssyc.common.appupdate.AppUpdateUtil;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.ScreenUtils;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.utils.WxAppUtils;
import com.ssyc.student.R;
import com.ssyc.student.bean.HomeInfo;
import com.ssyc.student.util.RecordTimeUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

import static com.ssyc.common.utils.UiUtils.getContext;

/**
 * 学生端主界面
 */
@Route(path = "/student/StudentMainActivity")
public class StudentMainActivity extends BaseActivity implements View.OnClickListener {

    //加载框布局
    private RelativeLayout rlLoading;

    //背景
    private ImageView lvBg;

    //新概念2
    private ImageView lvGoldNewConcept;
    //练习
    private ImageView lvHomework;
    //题库
    private ImageView lvQuestionBank;
    //成就
    private ImageView lvAchievement;
    //通知
    private ImageView lvNotification;
    //等级
    private TextView tvLever;

    //展示精力值的文字
    private TextView tvEnergy;

    //头像
    private CircleImageView lvHead;
    //金币数
//    private TextView tvGold;
//    //星星数
//    private TextView tvStar;
    //屏幕右边顶部的菜单
    private ImageView lvTopMemu;
    //喂食
    private ImageView lvFeed;
    //百宝箱
    private ImageView lvTreasure;
    //补给站
    private ImageView lvDepot;
    //朋友
    private ImageView lvFriends;
    //消息
    private ImageView lvMessage;

    //屏幕中间包含所有宠物动画的相对布局
    private RelativeLayout rlAllPet;

    //宠物的底图和套装
    private ImageView ivClothing;
    //帽子
    private ImageView ivHat;
    //眼镜
    private ImageView ivGrass;
    //项链
    private ImageView ivJingshi;

    //打卡记录
    private ImageView lvRecord;


    //是否是第一次进入
    private boolean isFirst = true;

    //动画对象
    private ObjectAnimator animator;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_main;
    }

    @Override
    protected void init() {

        showContent();

        //检查更新
        AppUpdateUtil.updateVersion(this);

        //初始化视图
        initView();

        //请求服务器获取首页数据
        http();

        //注册云信状态监听器
//        IMUtils.registerObservers(true);

    }


    /**
     * 初始化视图的方法
     */
    private void initView() {
        lvBg = findViewById(R.id.lv_bg);
        lvGoldNewConcept = findViewById(R.id.lv_gold_new_concept);
        tvLever = findViewById(R.id.tv_lever);
        lvGoldNewConcept.setOnClickListener(this);
        lvHomework = findViewById(R.id.lv_homework);
        lvHomework.setOnClickListener(this);
        lvQuestionBank = findViewById(R.id.lv_question_bank);
        lvQuestionBank.setOnClickListener(this);
        lvAchievement = findViewById(R.id.lv_achievement);
        lvAchievement.setOnClickListener(this);
        lvNotification = findViewById(R.id.lv_notification);
        lvNotification.setOnClickListener(this);
        //精力值
        tvEnergy = findViewById(R.id.tv_energy);
        //动态适配图片的大小
        int screenWidth = ScreenUtils.getScreenWidth(this);
        //屏幕宽度的五分之一减去左右边距
        int lvBottomItemWidth = (screenWidth - 16) / 5 - 24;
        RelativeLayout.LayoutParams lpBottom = new RelativeLayout.LayoutParams(lvBottomItemWidth, lvBottomItemWidth);
        lpBottom.addRule(RelativeLayout.CENTER_IN_PARENT);
        //设置底部的菜单图片的大小
        lvGoldNewConcept.setLayoutParams(lpBottom);
        lvHomework.setLayoutParams(lpBottom);
        lvQuestionBank.setLayoutParams(lpBottom);
        lvAchievement.setLayoutParams(lpBottom);
        lvNotification.setLayoutParams(lpBottom);

        //头像
        lvHead = findViewById(R.id.lv_head);
        lvHead.setOnClickListener(this);
        //屏幕右边顶部的菜单
        lvTopMemu = findViewById(R.id.lv_top_memu);
        lvTopMemu.setOnClickListener(this);
        //喂食
        lvFeed = findViewById(R.id.lv_feed);
        lvFeed.setOnClickListener(this);
        //百宝箱
        lvTreasure = findViewById(R.id.lv_treasure);
        lvTreasure.setOnClickListener(this);
        //补给站
        lvDepot = findViewById(R.id.lv_depot);
        lvDepot.setOnClickListener(this);
        //好友
        lvFriends = findViewById(R.id.lv_friends);
        lvFriends.setOnClickListener(this);
        //消息
        lvMessage = findViewById(R.id.lv_message);
        lvMessage.setOnClickListener(this);

        //底图和背景公用
        ivClothing = findViewById(R.id.iv_clothing);
        //帽子
        ivHat = findViewById(R.id.iv_hat);
        //眼镜
        ivGrass = findViewById(R.id.iv_glass);
        //项链
        ivJingshi = findViewById(R.id.iv_jingshi);

        //动态配置屏幕右边顶部的各菜单栏大小
        int topItemSize = lvBottomItemWidth * 56 / 62;
        LinearLayout.LayoutParams lpTopItem = new LinearLayout.LayoutParams(topItemSize, topItemSize * 110 / 94);
        lpTopItem.bottomMargin = 12;
        lvFeed.setLayoutParams(lpTopItem);
        lvTreasure.setLayoutParams(lpTopItem);
        lvDepot.setLayoutParams(lpTopItem);
        lvFriends.setLayoutParams(lpTopItem);
        lvMessage.setLayoutParams(lpTopItem);

        LinearLayout.LayoutParams lpTop = new LinearLayout.LayoutParams(topItemSize * 40 / 56, topItemSize * 40 / 56);
        lpTop.bottomMargin = 24;
        lvTopMemu.setLayoutParams(lpTop);

        //宠物图片
        rlAllPet = findViewById(R.id.rl_all_pet);
        RelativeLayout.LayoutParams lpAll = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lpAll.addRule(RelativeLayout.CENTER_HORIZONTAL);
        lpAll.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

        //计算宠物在屏幕中的位置
        int screenHeight = ScreenUtils.getScreenHeight(this);
        int bottomMarginSize = screenHeight * 100 / 668;
        lpAll.bottomMargin = bottomMarginSize;
        rlAllPet.setLayoutParams(lpAll);

        //打卡记录
        lvRecord = findViewById(R.id.lv_record);
        lvRecord.setOnClickListener(this);
        LinearLayout.LayoutParams lpRecord = new LinearLayout.LayoutParams(topItemSize * 42 / 56, topItemSize * 42 / 56);
        lpRecord.leftMargin = 12;
        lvRecord.setLayoutParams(lpRecord);

        rlLoading = findViewById(R.id.loading);
        rlLoading.setVisibility(View.VISIBLE);
    }

    /**
     * 请求服务器获取首页数据
     */
    private void http() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "3");
        map.put("role", AccountUtils.getRole(this));
        map.put("acc", AccountUtils.getAccount(this));
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "8");
//        LogUtils.iTag("test", "请求参数是:");
//        LogUtils.iTag("test", "type=3&role=" + AccountUtils.getRole(this) + "&acc=" + AccountUtils.getAccount(this)
//                + "apptoken=" + AccountUtils.getToken(this) + "&platform=8");

        HttpUtils.post(HttpAdress.STHOME, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {

                //背景设置完毕后隐藏加载框,解决加载空白的问题
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }

                if (!TextUtils.isEmpty(response)) {
                    Log.i("test", "首页：" + response);

                    HomeInfo info = null;

                    try {
                        info = GsonUtil.jsonToBean(response, HomeInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }


                    if (null != info) {
                        //等级提升的标识
                        if (info.getLevel() != 0) {
                            //标识等级提升
                            UiUtils.Toast("恭喜你的宠物升到" + info.getLevel() + "级啦", false);
                        }

                        List<HomeInfo.DataBean> data = info.getData();

                        if (null != data && data.size() > 0) {

                            Log.i("test", "数据是" + GsonUtil.listToJson(data));

                            HomeInfo.DataBean dataBean = data.get(0);

                            //保存头像url
                            SPUtil.put(StudentMainActivity.this, SpKeys.HEADIMG, dataBean.getStudent_icon());

                            //保存智勇欢爱
                            SPUtil.put(StudentMainActivity.this, SpKeys.WISDOM, dataBean.getWisdom());
                            SPUtil.put(StudentMainActivity.this, SpKeys.BRAVE, dataBean.getBrave());
                            SPUtil.put(StudentMainActivity.this, SpKeys.JOY, dataBean.getJoy());
                            SPUtil.put(StudentMainActivity.this, SpKeys.LOVE, dataBean.getLove());

                            //设置除了中间宠物部分的其它控件的数据
                            setOtherPageData(dataBean);

                            //设置宠物的相关信息
                            setPetInfo(info);
                        }
                    }
                }
            }
        });
    }

    /**
     * 设置除页面中间宠物信息的其它数据
     *
     * @param info
     */
    private void setOtherPageData(HomeInfo.DataBean info) {
        //背景
        ImageUtil.displayImage(this, lvBg, info.getBackground_url(), R.drawable.student_main_bg);

        //头像
        ImageUtil.displayImage(this, lvHead, info.getStudent_icon());

        //等级
        tvLever.setText("LV" + info.getLevel());

        //精力值
        tvEnergy.setText(info.getEnergy() + "/" + info.getMax_energy());
    }

    /**
     * 设置宠物的相关信息
     *
     * @param info
     */
    private void setPetInfo(HomeInfo info) {

        List<HomeInfo.DataFashion0Bean> dataFashion_0 = info.getDataFashion_0();
        List<HomeInfo.DataFashion1Bean> dataFashion_1 = info.getDataFashion_1();
        List<HomeInfo.DataFashion2Bean> dataFashion_2 = info.getDataFashion_2();
        List<HomeInfo.DataFashion3Bean> dataFashion_3 = info.getDataFashion_3();


        //套装
        if (dataFashion_0 == null || dataFashion_0.size() == 0) {
            //表示没有套装
            //设置底图
            String type = SPUtil.getString(this, SpKeys.SERVICEPETTYPE);
            LogUtils.iTag("test", "储存的类型是:" + type);

            if ("1".equals(type)) {
                //狗
                ivClothing.setImageResource(R.drawable.stu_pet_dog);
            } else if ("2".equals(type)) {
                //猫
                ivClothing.setImageResource(R.drawable.stu_pet_cat);
            } else if ("3".equals(type)) {
                //怪物
                ivClothing.setImageResource(R.drawable.stu_pet_monster);
            } else if ("4".equals(type)) {
                //熊猫
                ivClothing.setImageResource(R.drawable.stu_pet_panda);
            }

            //设置帽子,眼镜,项链
            if (null != dataFashion_1 && dataFashion_1.size() > 0) {
                HomeInfo.DataFashion1Bean dataFashion1Bean = dataFashion_1.get(0);
                ivHat.setVisibility(View.VISIBLE);
                ImageUtil.displayImage(this, ivHat, dataFashion1Bean.getUrl());
            } else {
                ivHat.setVisibility(View.GONE);
            }


            if (null != dataFashion_2 && dataFashion_2.size() > 0) {
                HomeInfo.DataFashion2Bean dataFashion2Bean = dataFashion_2.get(0);
                ivGrass.setVisibility(View.VISIBLE);
                ImageUtil.displayImage(this, ivGrass, dataFashion2Bean.getUrl());
            } else {
                ivGrass.setVisibility(View.GONE);
            }


            if (null != dataFashion_3 && dataFashion_3.size() > 0) {
                HomeInfo.DataFashion3Bean dataFashion3Bean = dataFashion_3.get(0);
                ivJingshi.setVisibility(View.VISIBLE);
                ImageUtil.displayImage(this, ivJingshi, dataFashion3Bean.getUrl());
            } else {
                ivJingshi.setVisibility(View.GONE);
            }

        } else {
            //有套装
            if (dataFashion_0.size() > 0) {
                HomeInfo.DataFashion0Bean dataFashion0Bean = dataFashion_0.get(0);
                ImageUtil.displayImage(this, ivClothing, dataFashion0Bean.getUrl());
            }
            //清除帽子,眼镜,项链
            ivHat.setVisibility(View.GONE);
            ivGrass.setVisibility(View.GONE);
            ivJingshi.setVisibility(View.GONE);
        }

        //如果是第一次进入的时候,让包含宠物的整体布局做屏幕两侧的动画效果处理
        if (isFirst) {
            startAnim();
        }
    }


    /**
     * 执行动画的方法
     */
    private void startAnim() {
        //执行从中间到屏幕右边动画,然后执行从右往左的动画
        int disx = ScreenUtils.getScreenWidth(this) / 2 - UiUtils.dp2px(80);
        animator = ObjectAnimator.ofFloat(rlAllPet, "translationX", 0f, disx, -disx, 0f);
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);
        animator.setDuration(4000);
        rlAllPet.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        animator.start();
    }


    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {

        int id = v.getId();

        if (id == R.id.lv_head) {
            //头像
            UiUtils.startActivity(this, StudentPersonInfoActivity.class);
        } else if (id == R.id.lv_gold_new_concept) {
            //新概念2
            UiUtils.startActivity(this, StudentNewConceptTwoActivity.class);
        } else if (id == R.id.lv_homework) {
            //练习
            UiUtils.startActivity(this, StudentHomeWorkActivity.class);
        } else if (id == R.id.lv_question_bank) {
            //测评
//            ARouter.getInstance().build("/teacherappraisal/TkStudentrAppraisalMainActivity").navigation();
            //跳转金牌单词王小程序
            WxAppUtils.launchWeApp(getContext());
        } else if (id == R.id.lv_achievement) {
            //成就
            UiUtils.startActivity(this, StudentAchievementActivity.class);
        } else if (id == R.id.lv_notification) {
            //通知
            UiUtils.startActivity(this, StudentNotifyActivity.class);
        } else if (id == R.id.lv_top_memu) {
            //设置界面
            UiUtils.startActivity(this, StudentSettingActivity.class);
        } else if (id == R.id.lv_treasure) {
            //百宝箱
            UiUtils.startActivity(this, StudentTreasureChestActivity.class);
        } else if (id == R.id.lv_depot) {
            //补给站
            UiUtils.startActivity(this, StudentDepotActivity.class);
        } else if (id == R.id.lv_friends) {
            //好友
            UiUtils.startActivity(this, StudentFriendsActivity.class);
        } else if (id == R.id.lv_message) {
            //消息
            UiUtils.startActivity(this, StudentMessageActivity.class);
        } else if (id == R.id.lv_record) {
            //打卡记录
            UiUtils.startActivity(this, StudentPunchCardActivity.class);
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onResume() {
        super.onResume();
        //在次进入该页面时重新请求页面数据执行动画
        if (!isFirst) {
            http();
            if (animator != null) {
                animator.resume();
            }

            //进入开始计时
            RecordTimeUtil.httpEnterAppTime(this);
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onPause() {
        super.onPause();
        //停止移动
        stopAnim();
    }

    /**
     * 停止动画的方法
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void stopAnim() {
        if (animator != null) {
            animator.pause();
        }
        isFirst = false;
    }

    @Override
    protected void onDestroy() {
        if (animator != null) {
            if (animator.isRunning()) {
                animator.cancel();
            }
            animator = null;
        }

        //退出停止计时
        RecordTimeUtil.httpExitAppTime(SPUtil.getString(this, SpKeys.TIMERECORD), this);
        super.onDestroy();
    }

    /**
     * 接受事件的方法
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        //退出登录
        if (null != busInfo && StudentSettingActivity.FINISH.equals(busInfo.vpScoll)) {

            ARouter.getInstance().build("/main/ChooseRoleActivity").navigation();
            finish();
        }
    }
}
